import { loginApi, getUserInfoApi, getDetailUserInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    // 清除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 设置用户基本资料
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    // 清除用户基本资料
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 发送登录请求，获取token
    async loginActions(context, payload) {
      const res = await loginApi(payload)
      context.commit('setToken', res)
    },
    // 发送获取用户资料请求，拿到userInfo
    async getUserInfoActions(context) {
      const res = await getUserInfoApi()
      const res2 = await getDetailUserInfoApi(res.userId)
      context.commit('setUserInfo', { ...res, ...res2 })
    },
    // 退出操作
    quitActions(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}

